package com.yzt.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yzt.base.kit.Base;
import com.yzt.config.websocket.WebSocketService;
import com.yzt.sys.entity.Role;
import com.yzt.sys.entity.UserRole;
import com.yzt.sys.service.IRoleService;
import com.yzt.sys.service.IUserRoleService;

/**
 * <p>
 * 用户_角色关联表 前端控制器
 * </p>
 *
 * @author Y
 * @since 2021-01-21
 */
@RestController
@RequestMapping("/sys/userRole")
public class UserRoleController {

	@Autowired
	private IUserRoleService userRoleService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private WebSocketService webSocketService;

	@PostMapping("")
	@Transactional(rollbackFor = Exception.class)
	public Base<Object> save(Long[] roleIds, Long userId) throws Exception {
		userRoleService.remove(Wrappers.<UserRole>lambdaQuery().eq(UserRole::getUserId, userId));
		boolean b = true;
		if (roleIds != null)
			for (Long roleId : roleIds) {
				UserRole ur = new UserRole();
				ur.setUserId(userId);
				ur.setRoleId(roleId);
				b = userRoleService.save(ur);
				if (!b)
					throw new Exception("权限分配错误");
			}
		webSocketService.sendMsgToAll(JSON.toJSONString(Base.ok(601, "刷新权限")));
		return Base.ok();
	}

	@GetMapping("rolelist")
	public Base<Map<String, Object>> rolelist(Long userId) {
		List<Role> list = roleService.list();
		List<Long> roleIds = userRoleService.listObjs(
				Wrappers.<UserRole>lambdaQuery().select(UserRole::getRoleId).eq(UserRole::getUserId, userId), a -> {
					return Long.valueOf(a.toString());
				});
		List<Map<String, Object>> roleList = new ArrayList<>();
		for (Role role : list) {
			Map<String, Object> map = new HashMap<>();
			map.put("value", role.getId());
			map.put("title", role.getName());
			roleList.add(map);
		}
		Map<String, Object> data = new HashMap<>();
		data.put("roleData", roleList);
		data.put("hasRole", roleIds);
		return Base.okData(data);
	}

}
